﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using DataBaseAccessLib;
using BusinessModel;
using BusinessModel.EntityModel;

namespace SDZJ.ManagerView.SystemManager
{
    public partial class AddNewUser : System.Web.UI.Page
    {
        #region********变量定义**************
        /// <summary>
        /// 当前页面
        /// </summary>
        public int currentPage = 1;

        /// <summary>
        /// 查询条件
        /// </summary>
        public string condition = "";
        /// <summary>
        /// 实例化操作类
        /// </summary>
        //MaterialHelper cMaterailList = new MaterialHelper();
        /// <summary>
        ///日志信息实体
        /// </summary>
        //LogInfo logInfo = new LogInfo();
        /// <summary>
        ///日志信息操作类
        /// </summary>
        // LogHelper cLog = new LogHelper();
        /// <summary>
        /// 用户id  
        /// </summary>
        public string currentUserID = "";
        /// <summary>
        /// 用户名称
        /// </summary>
        private string currentUserName = "";


      
        #endregion***************************
        public string studentID = "";              //学生ID        STUDENT_NUMBER
        public string centerID = "";               //分中心ID      BRANCH_SCHOOL_ID

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string keyword = searchKey.Text;
                condition = "where a.BRANCH_SCHOOL_ID=b.BRANCH_SCHOOL_ID";
                if (keyword != "")
                {
                    condition = condition + " and (a.Name like '%" + keyword + "%' or b.NAME like '%" + keyword + "%')";
                }
                GetDataSource(condition);
            }
        }
        //#region******方法**********
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="condition"></param>
        private void GetDataSource(String condition)
        {
            //排序字段
            string sortExpression = "STUDENTID";
            //排序方式
            string sortDirection = "";
            if (this.GridView1.Attributes["SortExpression"] != null)
            {
                sortExpression = this.GridView1.Attributes["SortExpression"];
                sortDirection = this.GridView1.Attributes["SortDirection"];
            }
            this.AspNetPager1.PageChanged -= AspNetPager_PageChanged;


            DataTable table = GetAllUserList(AspNetPager1.PageSize, currentPage, AspNetPager1, sortExpression, sortDirection, condition);
            if (table != null)
            {
                GridView1.DataSource = table.DefaultView;
                GridView1.DataBind();
            }

            if (currentPage > 1)
            {
                AspNetPager1.FirstPageText = "<img src=../../images/page02.gif border=0 valign=middle hspace=3>";
                AspNetPager1.PrevPageText = "<img src=../../images/page01.gif border=0 valign=middle hspace=3>";
            }
            else
            {
                AspNetPager1.FirstPageText = "<img src=../../images/page05.gif border=0 valign=middle hspace=3>";
                AspNetPager1.PrevPageText = "<img src=../../images/page06.gif border=0 valign=middle hspace=3>";
            }

            if (currentPage == AspNetPager1.PageCount || AspNetPager1.PageCount == 0)
            {
                AspNetPager1.LastPageText = "<img src=../../images/page08.gif border=0 valign=middle hspace=3>";
                AspNetPager1.NextPageText = "<img src=../../images/page07.gif border=0 valign=middle hspace=3>";
            }
            else
            {
                AspNetPager1.LastPageText = "<img src=../../images/page04.gif border=0 valign=middle hspace=3>";
                AspNetPager1.NextPageText = "<img src=../../images/page03.gif border=0 valign=middle hspace=3>";
            }

            this.AspNetPager1.PageChanged += AspNetPager_PageChanged;
        }
        //gridview行点击事件
        protected override void Render(HtmlTextWriter writer)
        {
            //string postSc = ClientScript.GetPostBackEventReference(GridView1, "Select$" +row.RowIndex.ToString(), true);
           // e.Row.Attributes.Add("onclick", e.Row.ClientID.ToString() + ".checked=true;selectx(this);" + postSc + "");//点击行变色

            foreach (GridViewRow row in this.GridView1.Rows)
            {

                if (row.RowType == DataControlRowType.DataRow)
                {
                    string postSc = ClientScript.GetPostBackEventReference(this.GridView1, "Select$" + row.RowIndex.ToString(), true);
                    row.Attributes.Add("onclick", row.ClientID.ToString() + ".checked=true;selectx(this);" + postSc + "");//点击行变色
                }
            }
            base.Render(writer);

        }
        /// <summary>
        /// 行绑定事件
        /// </summary>   
        protected void gvInfo_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
              
               

            }
        }
        protected void AspNetPager_PageChanged(object sender, EventArgs e)
        {
            currentPage = AspNetPager1.CurrentPageIndex; // 记录列表当前页码
            txtCurrentPage.Value = currentPage.ToString();
            GetDataSource(condition);   // 绑定所有信息
        }

        public DataTable GetAllUserList(int pageSize, int currentPage, Wuqi.Webdiyer.AspNetPager pager, string sortExpression, string sortDirection, string condition)
        {
            int totalPage = 0, totalRow = 0;//总页数，总记录数
            SQLScript sqlScript = new SQLScript();
            DataTable table = null;

            try
            {
                //if (mc.KeyExist("UserList" + currentPage))
                //{
                //    //获取
                //    table = (DataTable)mc.GetObject("materialList" + currentPage);
                //    totalRow = (int)mc.GetObject("materialListTotalRow");
                //}
                //else
                // {
                IDBAccess DB = DBFactory.GetDBAccess(OConfig.SysDBType, OConfig.DBConnection);
                int startIndex, endIndex;
                string strCol = " a.STUDENT_NUMBER,a.Name,a.STUDENTID,a.BRANCH_SCHOOL_ID,b.NAME as BRANCH_SCHOOL_NAME";
                OConfig.GetStartRowNum(" EL_STUDENT a,el_branchschool b ", condition, currentPage, pageSize, out startIndex, out endIndex, out totalPage, out totalRow);
                string sqlCommand = sqlScript.QueryByDividePage(" EL_STUDENT a ,el_branchschool b", condition, strCol, sortExpression + " " + sortDirection, startIndex, endIndex);
                table = DB.ExecuteDataTable(sqlCommand, CommandType.Text, null);

                //存储
                //mc.SetObject("materialList" + currentPage, table);
                //mc.SetObject("materialListTotalRow", totalRow);
                // }

                pager.RecordCount = totalRow;
                if (currentPage > pager.PageCount)
                {
                    currentPage = pager.PageCount;
                }
                if (currentPage == 0)
                {
                    currentPage = 1;
                }
                pager.CurrentPageIndex = currentPage;
            }
            catch (Exception exp)
            {
                table = null;
            }
            finally
            {
               // pager.CustomInfoHTML = "共<font color=red>" + pager.RecordCount + "</font>条数据&nbsp;&nbsp;&nbsp;&nbsp;当前<font color=red>" + pager.CurrentPageIndex + "/" + pager.PageCount + "</font>页";
                pager.CustomInfoHTML = "当前<font color=red>" + pager.CurrentPageIndex + "/" + pager.PageCount + "</font>页";
            }
            //mc.ClosePool();
            return table;
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string keyword = searchKey.Text;
            if (keyword == "")
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", "alert('请输入关键字');", true);
                return;
            }
            condition = "where a.BRANCH_SCHOOL_ID=b.BRANCH_SCHOOL_ID";
            if (keyword != "")
            {
                condition = condition + " and (a.Name like '%" + keyword + "%' or b.NAME like '%" + keyword + "%')";
            }
            GetDataSource(condition);
        }

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string userName = "";   //名称
            string policeID = "";     //警号
            policeID = GridView1.Rows[GridView1.SelectedIndex].Cells[0].Text;
            userName=GridView1.Rows[GridView1.SelectedIndex].Cells[1].Text;

            UserName.Text = userName + policeID;
            NickName.Text = userName;
            Password1.Text = "";
            Password2.Text = "";
            CheckBox1.Checked = false;
            CheckBox3.Checked = false;
           

           // studentID = GridView1.DataKeys[GridView1.SelectedIndex].Values["STUDENTID"].ToString();
           // centerID = GridView1.DataKeys[GridView1.SelectedIndex].Values["BRANCH_SCHOOL_ID"].ToString();

        }

        protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
        {
            //注册行单击事件 
            //e.Row.Attributes.Add("onclick", "javascirpt:__doPostBack('GridView1','Select$" + e.Row.RowIndex + "')"); 
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            string guid=OConfig.GetGUID();      //用户ID
            string userName = "";     //名称
            string userPass = "";     //密码
            string niceName = "";     //昵称

            int  isEnable = 0;     //是否禁止使用
            int  isLock = 0;       //是否锁定

            int idx = GridView1.SelectedIndex;
            studentID = GridView1.Rows[GridView1.SelectedIndex].Cells[0].Text;
            centerID = GridView1.DataKeys[idx].Values["BRANCH_SCHOOL_ID"].ToString();

            if (CheckBox1.Checked)
            {
                isEnable = 1;
            }
            if (CheckBox3.Checked)
            {
                isLock = 1;
            }

            userPass = Password1.Text;
            userName = UserName.Text;
            niceName = NickName.Text;



            Security secPass=new Security();
            string enuserPass = secPass.Encrypt(userPass);


            UserClass userInf=new UserClass();
            userInf.userid = guid;
            userInf.branch_school_id = centerID;
            userInf.username = userName;
            userInf.nicename = niceName;
            userInf.password = enuserPass;
            string cTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ");
          //  userInf.reg_date = cTime;      //当前时间
            userInf.student_number = studentID;
            userInf.locked = isLock;
            userInf.disabled = isEnable;
            userInf.description = "";
           //userInf.expire_date = cTime;

            EntityOprHelper helper = new EntityOprHelper();
            UserClass _Tmp = helper.GetEntity<UserClass>(userInf.student_number);

            if (_Tmp != null)
            {
                //提示用户已经存在
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", "AddSuccess(0);", true);
                return;
            }
            bool isSucess= helper.AddEntity<UserClass>(userInf);
            if (isSucess)
            {
                //提示成功
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", "AddSuccess(1);", true);
            }
        }

    }
}